package com.htgd.gardenexpo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.htgd.gardenexpo.entity.GeBaseUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author ：hejing
 * @date ：Created in 2021/6/22 14:41
 * @description：token生成工具类
 * @modified By：`
 * @version: 1.0
 */
@Api(tags = "token签名")
@RestController
@RequestMapping("/utils/token")
public class TokenUtil {
//    private static final long EXPIRE_TIME= 5*60*1000;
    private static final long EXPIRE_TIME= 25*60*60*1000;
//    private static final long EXPIRE_TIME= 6*1000;
    private static final String TOKEN_SECRET="yuhuaxian";  //密钥盐

    /**
     * 签名生成
     * @param user
     * @return
     */
    @ApiOperation("签名")
    @GetMapping("/sign")
    public static String sign(GeBaseUser user){
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("auth0")
                    .withClaim("username", user.getPhone())
                    .withExpiresAt(expiresAt)
                    // 使用了HMAC256加密算法。
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e){
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 签名验证
     * @param token
     * @return
     */
    public static boolean verify(String token){
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT jwt = verifier.verify(token);
           /* System.out.println("认证通过：");
            System.out.println("username: " + jwt.getClaim("username").asString());
            System.out.println("过期时间：      " + jwt.getExpiresAt());*/
            if (System.currentTimeMillis()-jwt.getExpiresAt().getTime()>EXPIRE_TIME){
                return  false;
            }
            return true;
        } catch (Exception e){
            return false;
        }
    }

    public static String getUsernameFromToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (Exception e) {
//            e.printStackTrace();
            return null;
        }
    }
}
